package com.example.administrator.yuejian35.Home.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Explode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.yuejian35.Config;
import com.example.administrator.yuejian35.Home.HomeModel;
import com.example.administrator.yuejian35.Home.SampleListener;
import com.example.administrator.yuejian35.Home.adapter.RecyclerBaseAdapter;
import com.example.administrator.yuejian35.Home.adapter.RecyclerItemViewHolder;
import com.example.administrator.yuejian35.Home.bean.Course;
import com.example.administrator.yuejian35.Home.bean.Result;
import com.example.administrator.yuejian35.MainActivity;
import com.example.administrator.yuejian35.RoundTransform;
import com.example.administrator.yuejian35.Home.bean.Master;
import com.example.administrator.yuejian35.R;
import com.example.administrator.yuejian35.button.ShineButton;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.ListVideoUtil;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.squareup.picasso.Picasso;

import java.util.List;

import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MasterActivity extends AppCompatActivity {
    private TextView name,intro,course,fans,phone;
    private ImageView pic;
    private Context context;
    private Master master;

    private ShineButton guanzhu;

    //private VideoAdapter adapter;
    private RecyclerView rv;

    private FrameLayout videoFullContainer;

    private LinearLayoutManager linearLayoutManager;

    private RecyclerBaseAdapter recyclerBaseAdapter;

    //private List<Course> dataList = new ArrayList<>();

    private ListVideoUtil listVideoUtil;
    private int lastVisibleItem;
    private int firstVisibleItem;

    private String type,Uid,id;

    private SharedPreferences settings;
    private SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
            getWindow().setEnterTransition(new Explode());
            getWindow().setExitTransition(new Explode());
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master);

        name = (TextView) findViewById(R.id.master_mname);
        intro = (TextView) findViewById(R.id.master_intro);
        course = (TextView) findViewById(R.id.master_course);
        fans = (TextView) findViewById(R.id.master_fans);
        phone = (TextView) findViewById(R.id.master_tel);
        pic = (ImageView) findViewById(R.id.master_photo);
        rv = (RecyclerView) findViewById(R.id.rv_master_video);
        guanzhu = (ShineButton) findViewById(R.id.master_btn_colle);
        videoFullContainer = (FrameLayout) findViewById(R.id.video_full_container);

        MainActivity mainActivity = new MainActivity();
        Uid = mainActivity.getUserId();


        master = getIntent().getParcelableExtra("master");

        if (master!=null){
            name.setText(master.getCoachname());
            intro.setText(master.getCoachintro());
            course.setText(master.getCoachid());
            fans.setText(master.getCoachattention());
            phone.setText(master.getCoachphone());

            if(!master.getCoachpic().equals("")){
                Picasso.with(context)
                        .load(Config.MasterImages_URL+master.getCoachpic())
                        .transform(new RoundTransform(100))
                        .into(pic);
            }

        }
        ButterKnife.bind(this);

        if (guanzhu != null)
            guanzhu.init(this);

        guanzhu.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(View view, final boolean checked) {
                type = String.valueOf(checked);

                if(type.equals("true")){
                    String coachid =master.getCoachid();
                    HomeModel homeModel = new HomeModel();
                    Call call = homeModel.master_collect(coachid,Uid,"true","");
                    call.enqueue(new Callback<Result>() {
                        @Override
                        public void onResponse(Call<Result> call, Response<Result> response) {
                            Toast.makeText(MasterActivity.this,"收藏成功！！！",Toast.LENGTH_SHORT).show();
                            Log.v("联网","true");
                            type = String.valueOf(checked);
                            settings = getSharedPreferences(Uid, Context.MODE_PRIVATE);
                            //2、让setting处于编辑状态
                            editor = settings.edit();
                            //3、存放数据
                            editor.putString("master_collect","true");
                            editor.putString("master_collect_id",response.body().getResult());
                            //4、完成提交
                            editor.commit();
                        }

                        @Override
                        public void onFailure(Call<Result> call, Throwable t) {
                            Log.v("联网","失败！！！");
                        }
                    });
                }

                else if(type.equals("false")){
                    String coachid =master.getCoachid();
                    HomeModel homeModel = new HomeModel();
                    SharedPreferences get = getSharedPreferences(Uid, Context.MODE_PRIVATE);
                    id = get.getString("master_collect_id","");
                    Call call = homeModel.master_collect(coachid,Uid,"false",id);
                    call.enqueue(new Callback<Result>() {
                        @Override
                        public void onResponse(Call<Result> call, Response<Result> response) {
                            Toast.makeText(MasterActivity.this,"取消收藏成功！！！",Toast.LENGTH_SHORT).show();
                            Log.v("联网","false");

                            settings = getSharedPreferences(Uid, Context.MODE_PRIVATE);
                            //2、让setting处于编辑状态
                            editor = settings.edit();
                            //3、存放数据
                            editor.putString("master_collect","false");

                            //4、完成提交
                            editor.commit();
                        }

                        @Override
                        public void onFailure(Call<Result> call, Throwable t) {
                            Log.v("联网","失败！！！");
                        }
                    });

                }

            }
        });

        SharedPreferences getting = getSharedPreferences(Uid, Context.MODE_PRIVATE);
        //2、取出数据
        String bbb = getting.getString("master_collect","-1");

        if(bbb.equals("true")){
            guanzhu.setChecked(true);
        }

        InternetCourse();

        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem   = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                Debuger.printfLog("firstVisibleItem " + firstVisibleItem +" lastVisibleItem " + lastVisibleItem);
                //大于0说明有播放,//对应的播放列表TAG
                if (listVideoUtil.getPlayPosition() >= 0 && listVideoUtil.getPlayTAG().equals(RecyclerItemViewHolder.TAG)) {
                    //当前播放的位置
                    int position = listVideoUtil.getPlayPosition();
                    //不可视的是时候
                    if ((position < firstVisibleItem || position > lastVisibleItem)) {
                        //如果是小窗口就不需要处理
                        if (!listVideoUtil.isSmall() && !listVideoUtil.isFull()) {
                            //小窗口
                            int size = CommonUtil.dip2px(MasterActivity.this, 150);
                            //actionbar为true才不会掉下面去
                            listVideoUtil.showSmallVideo(new Point(size, size), true, true);
                        }
                    } else {
                        if (listVideoUtil.isSmall()) {
                            listVideoUtil.smallVideoToNormal();
                        }
                    }
                }
            }
        });

    }

    private void initVideoUtil(){
        listVideoUtil = new ListVideoUtil(MasterActivity.this);
        listVideoUtil.setFullViewContainer(videoFullContainer);
        listVideoUtil.setHideStatusBar(true);
        //小窗口关闭被点击的时候回调处理回复页面
        listVideoUtil.setVideoAllCallBack(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                Debuger.printfLog("Duration " + listVideoUtil.getDuration() + " CurrentPosition " +
                        listVideoUtil.getCurrentPositionWhenPlaying());
            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {
                super.onQuitSmallWidget(url, objects);
                //大于0说明有播放,//对应的播放列表TAG
                if (listVideoUtil.getPlayPosition() >= 0 && listVideoUtil.getPlayTAG().equals(RecyclerItemViewHolder.TAG)) {
                    //当前播放的位置
                    int position = listVideoUtil.getPlayPosition();
                    //不可视的是时候
                    if ((position < firstVisibleItem || position > lastVisibleItem)) {
                        //释放掉视频
                        listVideoUtil.releaseVideoPlayer();
                        recyclerBaseAdapter.notifyDataSetChanged();
                    }
                }

            }
        });

    }

    private void InternetCourse() {

        HomeModel homeModel = new HomeModel();
        Call call = homeModel.master_video(Integer.parseInt(master.getCoachid()));

        call.enqueue(new Callback<List<Course>>() {


            @Override
            public void onResponse(Call<List<Course>> call, Response<List<Course>> response) {

                List<Course> courselist = response.body();
                Log.v("名字",courselist.get(0).getCoursename());

                linearLayoutManager = new LinearLayoutManager(MasterActivity.this);
                rv.setLayoutManager(linearLayoutManager);

                //resolveData();

                recyclerBaseAdapter = new RecyclerBaseAdapter(MasterActivity.this, courselist);
                rv.setAdapter(recyclerBaseAdapter);


                initVideoUtil();

                recyclerBaseAdapter.setListVideoUtil(listVideoUtil);

            }

            @Override
            public void onFailure(Call<List<Course>> call, Throwable t) {

            }
        });

    }


    @Override
    public void onBackPressed() {
        if (listVideoUtil.backFromFull()) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        listVideoUtil.releaseVideoPlayer();
        GSYVideoPlayer.releaseAllVideos();
    }


}
